package com.mustafaiev.tair.mweather;

import java.util.List;

import android.app.PendingIntent;
import android.app.Service;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.IBinder;
import android.util.Log;
import android.widget.RemoteViews;

import com.mustafaiev.tair.mweather.exception.MWeatherParseException;
import com.mustafaiev.tair.mweather.forecast.Forecast;
import com.mustafaiev.tair.mweather.xml.MWeatherXMLParser;

/**
 * General Widget class Creation date: 24 Aug 2011 22:35:17
 * 
 * @author Tair Mustafaiev
 * 
 */
public class MWeatherWidget extends AppWidgetProvider {

	@Override
	public void onUpdate(final Context context,
			final AppWidgetManager appWidgetManager, final int[] appWidgetIds) {

		context.startService(new Intent(context, UpdateService.class));

		final Intent intent = new Intent(context,
				ForecastListViewActivity.class);
		intent.setAction(ForecastListViewActivity.ACTION_CLICK);
		intent.setAction("android.appwidget.action.APPWIDGET_UPDATE");
		final PendingIntent pendingIntent = PendingIntent.getActivity(context,
				0, intent, 0);
		final RemoteViews views = new RemoteViews(context.getPackageName(),
				R.layout.widget_layout);
		views.setOnClickPendingIntent(R.id.background, pendingIntent);
		appWidgetManager.updateAppWidget(appWidgetIds, views);
	}

	/**
	 * Mathod checks connection availability. Creation date: 7 Sep 2011 23:54:27
	 * 
	 * @param context
	 * @return true/false according with connection exists or not
	 */
	public static boolean isOnline(Context context) {
		ConnectivityManager connectivityManager = (ConnectivityManager) context
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
		if (networkInfo == null) {
			return false;
		}
		if (networkInfo.isConnected()) {
			return true;
		}
		return true;
	}

	public static class UpdateService extends Service {

		@Override
		public void onStart(final Intent intent, final int startId) {
			Log.i("onStart", "start");
			RemoteViews updateViews = null;

			try {
				updateViews = this.buildUpdate(this);
			} catch (final InterruptedException e) {
				Log.e("onStart", e.toString());
			}

			// Push update for this widget to the home screen
			final ComponentName thisWidget = new ComponentName(this,
					MWeatherWidget.class);
			final AppWidgetManager manager = AppWidgetManager.getInstance(this);
			manager.updateAppWidget(thisWidget, updateViews);
			Log.i("onStart", "done");
		}

		public RemoteViews buildUpdate(final Context context)
				throws InterruptedException {

			return this.updateView(context);

		}

		/**
		 * Method updates views Creation date: Aug 21 2011 23:46:36
		 * 
		 * @param context
		 * @param today
		 * @return
		 * @throws InterruptedException
		 */
		private RemoteViews updateView(final Context context)
				throws InterruptedException {
			RemoteViews updateViews = null;

			final MWeatherXMLParser forecastParser = new MWeatherXMLParser();
			List<Forecast> forecasts = null;
			if (MWeatherWidget.isOnline(context)) {
				try {
					forecasts = forecastParser.getParsedForecast("33345");

				} catch (final MWeatherParseException e) {
					Log.e("MWeatherWidget, method updateView()", e.toString());
				}
				final Forecast forecast = forecasts.get(0);
				updateViews = new RemoteViews(context.getPackageName(),
						R.layout.widget_layout);
				// calculate average temperature
				final String temperature = Integer
						.toString((forecast.getMinTemperature() + forecast
								.getMaxTemperature()) / 2);
				// calculate average pressure
				final String pressure = Integer.toString((forecast
						.getMinPressure() + forecast.getMaxPressure()) / 2);
				updateViews.setTextViewText(R.id.temperature, temperature
						+ "\u00B0C");
				updateViews.setTextViewText(R.id.pressure, pressure);
			} else {
				updateViews = new RemoteViews(context.getPackageName(),
						R.layout.widget_layout);
				updateViews.setTextViewText(R.id.temperature, "No Connection!");
			}
			return updateViews;
		}

		@Override
		public IBinder onBind(final Intent intent) {
			return null;
		}
	}
}
